package com.yaozheng.vocationaltraining.utils.http.okhttp;

import java.io.IOException;
import java.net.CookiePolicy;

import com.squareup.okhttp.Callback;
import com.squareup.okhttp.FormEncodingBuilder;
import com.squareup.okhttp.MediaType;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;
import com.squareup.okhttp.Response;
import com.yaozheng.vocationaltraining.app.VocationalTrainingApplication_;
import com.yaozheng.vocationaltraining.iview.IBaseView;
import com.yaozheng.vocationaltraining.utils.Constants;
import com.yaozheng.vocationaltraining.utils.ErrorUtils;
import com.yaozheng.vocationaltraining.utils.JsonUtils;
import com.yaozheng.vocationaltraining.utils.LogUtils;
import com.yaozheng.vocationaltraining.utils.TypeUtils;

import java.net.CookieManager;
import java.util.Iterator;
import java.util.Map;

import org.apache.commons.lang.NullArgumentException;

import net.sf.json.JSONObject;

public class OkHttpClientManager {
    private static OkHttpClientManager mInstance;
    private OkHttpClient mOkHttpClient;
    public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");

    private OkHttpClientManager() {
        mOkHttpClient = new OkHttpClient();
        // cookie enabled
        mOkHttpClient.setCookieHandler(new CookieManager(null,
                CookiePolicy.ACCEPT_ORIGINAL_SERVER));
        // mDelivery = new Handler(Looper.getMainLooper());
        // mGson = new Gson();
    }

    public static OkHttpClientManager getInstance() {
        if (mInstance == null) {
            synchronized (OkHttpClientManager.class) {
                if (mInstance == null) {
                    mInstance = new OkHttpClientManager();
                }
            }
        }
        return mInstance;
    }

    /**
     * post请求
     *
     * @param token
     * @param para
     * @param callback
     */
    public void post(String url, String token, Map<String, String> para,
                     Callback callback) {
        FormEncodingBuilder builder = new FormEncodingBuilder();
        if (para != null) {
            Iterator<String> keys = para.keySet().iterator();
            while (keys.hasNext()) {
                String key = keys.next();
                builder.add(key, para.get(key));
            }
        }
        // 创建okHttpClient对象
        Request.Builder requestBuilder = new Request.Builder().addHeader(
                "Content-Type", "application/json");
        if (token != null) {
            requestBuilder.addHeader("Token", token);
            requestBuilder.addHeader("Equip", getEquip());
        }
        Request request = requestBuilder
                .addHeader("Content-Type", "application/json").url(url)
                .post(builder.build()).build();
        mOkHttpClient.newCall(request).enqueue(callback);
    }

    /**
     * post请求
     *
     * @param token
     * @param callback
     */
    public void postJson(String url, String token, String jsonObject,
                         Callback callback) {
        RequestBody body = RequestBody.create(JSON, jsonObject);
        // 创建okHttpClient对象
        Request.Builder requestBuilder = new Request.Builder().addHeader(
                "Content-Type", "application/json");
        if (token != null) {
            requestBuilder.addHeader("Token", token);
            requestBuilder.addHeader("Equip", getEquip());
        }
        Request request = requestBuilder
                .addHeader("Content-Type", "application/json").url(url)
                .post(body).build();
        mOkHttpClient.newCall(request).enqueue(callback);
    }

    /**
     * 下载文件
     *
     * @param fileLength
     * @param fileLength
     * @param callback
     */
    public void downloadFile(String url, long fileLength, Callback callback) {
        Response response = null;
        Request request = null;
        try {
            Request.Builder requestBuilder = new Request.Builder().addHeader(
                    "Content-Type", "application/octet-stream");
            if (fileLength >= 0) {
                requestBuilder.addHeader("Range", "bytes=" + fileLength + "-");
            }
            request = requestBuilder
                    .addHeader("Content-Type", "application/octet-stream")
                    .url(url).get().build();
            response = mOkHttpClient.newCall(request).execute();
            callback.onResponse(response);
        } catch (Exception e) {
            callback.onFailure(request, new IOException(e.getMessage()));
        }
    }

    /**
     * IBaseView处理结果
     *
     * @author Administrator
     */
    public static class IBaseViewCallback implements Callback {
        IBaseView iBaseView;

        public IBaseViewCallback(IBaseView iBaseView) {
            this.iBaseView = iBaseView;
        }

        @Override
        public void onResponse(Response response) throws IOException {

            if (response.code() == 200) {
                if (iBaseView.isResponseResult()) {
                    String bodyContentStr = response.body().string();
                    LogUtils.println(bodyContentStr);
                    JSONObject resultSetJsonObject = JsonUtils
                            .getJsonObject(bodyContentStr);
                    if (0 == TypeUtils.getJsonInteger(resultSetJsonObject,
                            "error_code", -1)) {
                        iBaseView.responseSuccess(resultSetJsonObject);
                    } else {
                        String errorStr = TypeUtils.getJsonString(
                                resultSetJsonObject, "error_msg",
                                ErrorUtils.SERVER_CONNECTION_ERROR);iBaseView.responseError(errorStr);
                    }
                }
            } else if (response.code() == 401) {
                if (iBaseView.isResponseResult()) {
                    iBaseView.responseError("帐号已过期,请重新登录...");
                    iBaseView.tokenFail();
                }
            } else {
                if (iBaseView.isResponseResult()) {
                    iBaseView.responseError(ErrorUtils.SERVER_CONNECTION_ERROR
                            + response.code());
                }

            }
        }

        @Override
        public void onFailure(Request request, IOException e) {

            ErrorUtils.outErrorLog(e);
            if (iBaseView.isResponseResult()) {
                iBaseView.responseError(ErrorUtils.SERVER_CONNECTION_ERROR);
            }
        }
    }

    /**
     * post请求
     *
     * @param token
     * @param para
     */
    public void post(String url, String token, Map<String, String> para,
                     IBaseView iBaseView) {
        post(url, token, para, new IBaseViewCallback(iBaseView));
    }

    /**
     * 上传文件
     *
     * @param url
     * @param token
     * @param iBaseView
     * @param uploadContent
     */
    public void upload(String url, String token, IBaseView iBaseView,
                       byte[] uploadContent) {
        upload(url, token, new IBaseViewCallback(iBaseView), uploadContent);
    }

    /**
     * 上传文件
     *
     * @param url
     * @param token
     * @param callback
     * @param uploadContent
     */
    public void upload(String url, String token, Callback callback,
                       byte[] uploadContent) {
        // 创建okHttpClient对象
        Request.Builder requestBuilder = new Request.Builder().addHeader(
                "Content-Type", "application/json");
        if (token != null) {
            requestBuilder.addHeader("Token", token);
            requestBuilder.addHeader("Equip", getEquip());
        }
        RequestBody requestBody = RequestBody.create(
                MediaType.parse("application/octet-stream"), uploadContent);

        Request request = requestBuilder
                .addHeader("Content-Type", "application/octet-stream").url(url)
                .post(requestBody).build();
        mOkHttpClient.newCall(request).enqueue(callback);
    }

    /**
     * @param url
     * @param token
     * @param iBaseView
     */
    public void get(String url, String token, IBaseView iBaseView) {
        get(url, token, new IBaseViewCallback(iBaseView));
    }

    /**
     * post请求
     *
     * @param token
     * @param callback
     */
    public void get(String url, String token, Callback callback) {
        // 创建okHttpClient对象
        Request.Builder requestBuilder = new Request.Builder().addHeader(
                "Content-Type", "application/json");
        if (token != null) {
            requestBuilder.addHeader("Token", token);
            requestBuilder.addHeader("Equip", getEquip());
        }
        Request request = requestBuilder
                .addHeader("Content-Type", "application/json").url(url).get()
                .build();
        mOkHttpClient.newCall(request).enqueue(callback);
    }

    public String getEquip() {
        return VocationalTrainingApplication_.getInstance().getEquip();
    }


}
